package com.android.logcat;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Environment;
import android.text.TextUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author GYL
 * @version 1.0
 * @dateTime 2020/6/30-18:14
 * @description 日志文件写入
 */
/*public*/ class LoggerFileWrite implements LoggerMonitor {
  private Context mContext;
  private String mLogFilePath;
  private File mLogFile;
  
  public LoggerFileWrite(Context context, String logFilePath) {
    this.mContext = context;
    this.mLogFilePath = logFilePath;
  }
  
  /**
   * 获取应用程序名称
   * @param context
   * @return
   */
  private String getAppName(Context context) {
    try {
      PackageManager packageManager = context.getPackageManager();
      PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
      int labelRes = packageInfo.applicationInfo.labelRes;
      return context.getResources().getString(labelRes);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  
  /**
   * 获取SD卡路径
   */
  private String getLogFilePath() {
    File sdDir = null;
    //判断sd卡是否存在
    boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    if (sdCardExist) {
      //获取跟目录 Environment.getExternalStorageDirectory();
      if (VERSION.SDK_INT >= VERSION_CODES.FROYO) {
        sdDir = mContext.getExternalCacheDir();
      } else {
        sdDir = Environment.getExternalStorageDirectory();
      }
    } else {
      sdDir = mContext.getCacheDir();
    }
    return sdDir.toString();
  }
  
  private void createFile() {
    if (TextUtils.isEmpty(mLogFilePath)) {
      mLogFilePath = getLogFilePath();
    }
    String logFileName = getAppName(mContext);
    SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");
    logFileName += "_" + logfile.format(new Date(System.currentTimeMillis()));
    logFileName += "_log.txt";
    String rootPath = mLogFilePath + File.separator + "Log";
    File dir = new File(rootPath);
    if (!dir.exists()) {
      dir.mkdirs();
    }
    mLogFile = new File(rootPath, logFileName);
    if (!mLogFile.exists()) {
      try {
        mLogFile.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    LoggerConfig.getInstance().getLogger().d("LOG", "Log File : " + mLogFile.getAbsolutePath(),null);
  }
  
  public File getLogFile(){
    return mLogFile;
  }
  
  private synchronized void write(String content){
    if (mLogFile == null) {
      createFile();
    }
    FileOutputStream fos = null;
    ByteBuffer byteBuffer=null;
    try {
      fos = new FileOutputStream(mLogFile,true);
      FileChannel channel = fos.getChannel();
      if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        byteBuffer = StandardCharsets.UTF_8.encode(content);
      }else{
        byteBuffer = Charset.forName("UTF-8").encode(content);
      }
      while(byteBuffer.hasRemaining()){
        channel.write(byteBuffer);
      }
      byteBuffer.clear();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  
  @Override
  public void logger(@LoggerLevel String loggerLevel,String content) {
    write(content);
  }
}
